import matplotlib.pyplot as plt
import numpy as np
from config import *

plt.style.use('ggplot')
plt.rcParams['font.sans-serif'] = [u'SimHei']
plt.rcParams['axes.unicode_minus'] = False


def annotate(axes, string, xy):
    xy[-1] = xy[-1] - 100
    axes.annotate('PK' + string, xy=xy)


def load_log(day):
    times = []
    fans = []
    fans_add = []

    with open(log_dir + log.format(day), 'r') as f:
        counter = 0
        max_add = 0
        min_add = 1000
        times_batch = []
        fans_batch = []
        fans_add_batch = []
        first = True

        lines = f.readlines()
        for line in lines:
            txt = line.strip()
            if first:
                first = False
                continue

            counter += 1

            add = int(txt.split(" ")[3])
            min_add = min(add, min_add)
            max_add = max(add, max_add)

            times_batch.append(txt.split(" ")[1][:5])
            fans_batch.append(int(txt.split(" ")[2]))
            fans_add_batch.append(int(txt.split(" ")[3]))

            if counter % 40 == 0:
                times.append(times_batch)
                fans.append(fans_batch)
                fans_add.append(fans_add_batch)
                times_batch = []
                fans_batch = []
                fans_add_batch = []

            if counter % 40 != 0 and counter == len(lines) - 1:
                times.append(times_batch)
                fans.append(fans_batch)
                fans_add.append(fans_add_batch)

    return times, fans, fans_add, min_add, max_add, day


def plot():
    times, fans, fans_add, min_add, max_add, day = load_log()
    length = len(times)
    fig, axs = plt.subplots(length, 1, figsize=(12, 12))
    for i in range(length):
        axs[i].plot(times[i], fans_add[i],
                    ls='-',
                    lw=2.,
                    marker='o',
                    )
        axs[i].set_xticks(np.arange(len(times[i])))
        axs[i].set_xticklabels(times[i], rotation=45)
        axs[i].set_ylim(bottom=min_add - 20, top=max_add + 50)
        axs[i].set_ylabel('涨\n粉', rotation='horizontal', labelpad=16.)
        for x, y in zip(times[i], fans_add[i]):
            axs[i].annotate(y, [x, y + 10])

    axs[0].set_title('涨粉趋势(5分钟)-{}'.format(day))
    axs[length - 1].set_xlabel('时间', labelpad=6.)
    plt.subplots_adjust(hspace=0.5)

    plt.show()
    fig.savefig("img/img-{}.png".format(day), format="png")
